//
//  XHMyTeamTableViewController.m
//  KuWoCan
//
//  Created by 周小宏 on 2017/5/2.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "XHMyTeamTableViewController.h"
// Net Request
#import "NWMyTeamRequest.h"
//Model
#import "MyTeamListModel.h"
// Cell
#import "XHMyTeamTableViewCell.h"
//VC
#import "JinXCViewController.h"
#import "MuBWCViewController.h"

static NSString *const CellIdentifier = @"SystemCell";

@interface XHMyTeamTableViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) NSMutableArray<MyTeamListModel *> *dataArr;
@end

@implementation XHMyTeamTableViewController
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    [self loadRootData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Config UI
- (void)configUI {
    self.title = @"我的团队";
    self.view.backgroundColor = [UIColor whiteColor];

    [self initTable];
}

- (void)initTable {
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH - 64) style:UITableViewStylePlain];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.table.showsVerticalScrollIndicator = NO;
    self.table.showsHorizontalScrollIndicator = NO;
    self.table.estimatedRowHeight = 80;
    [self.view addSubview:self.table];
}

#pragma mark - Load data


#pragma mark - Data request
- (void)loadRootData {
    NWMyTeamRequest *request = [[NWMyTeamRequest alloc] init];
    [request startRequestMyTeamTotalListWithUserId:[Singleton shareInstance].userId];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            MyTeamListModel *model = [[MyTeamListModel alloc] initWithDictionary:result error:nil];
            model.level = 0;
            [self.dataArr addObject:model];
            [self.table reloadData];
        } else {
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}

/**
 获取下级数据

 @param userId 用户ID
 */
- (void)loadNextDataWithUserId:(NSString *)userId Completion:(void(^)(id result, NSString *message, id extension, BOOL succ))completion {
    NWMyTeamRequest *request = [[NWMyTeamRequest alloc] init];
    [request startRequestMyTeamDetailListWithCharacterId:userId];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        completion(result, message, extension, succ);
    }];
}

#pragma mark - Registration notice and release


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyTeamListModel *model = self.dataArr[indexPath.row];
    XHMyTeamTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[XHMyTeamTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.cargoButtonClicekd = ^(MyTeamListModel *teamModel) {
        JinXCViewController *vc = [[JinXCViewController alloc] init];
        vc.personId = teamModel.userId;
        vc.isOtherEntrance = YES;
        [self.navigationController pushViewController:vc animated:YES];
    };

    cell.targetButtonClicked = ^(MyTeamListModel *teamModel) {
        MuBWCViewController *vc = [[MuBWCViewController alloc] init];
        vc.personId = teamModel.userId;
        [self.navigationController pushViewController:vc animated:YES];
    };

    cell.teamModel = model;
    if (indexPath.row == 0) {
        [cell hideExtemdImage];
    }

    cell.indentationLevel = model.level;
    cell.indentationWidth = 20 * screenW_6;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MyTeamListModel *model = self.dataArr[indexPath.row];

    XHMyTeamTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    if (!model.totalPeopleNum || model.totalPeopleNum.isEmptyString || [model.totalPeopleNum isEqualToString:@"0"]) {
        return;
    }
//    开始下标
    NSUInteger startIndex = indexPath.row + 1;
//    结束下标
    __block NSUInteger endIndex = indexPath.row;
//    需要更新的数据下表集合
    NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:startIndex];
//    需要更新的Cell IndexPath
    NSMutableArray<NSIndexPath *> *indexArr = [NSMutableArray array];

    if (model.isUnfold) {
        [self.dataArr enumerateObjectsUsingBlock:^(MyTeamListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.level == model.level && idx > [self.dataArr indexOfObject:model]) {
                *stop = YES;
                return ;
            }
            if (obj.level > model.level && idx > [self.dataArr indexOfObject:model]) {
                [indexes addIndex:++endIndex];
                [indexArr addObject:[NSIndexPath indexPathForRow:endIndex inSection:0]];
            }
        }];
        [self.dataArr removeObjectsAtIndexes:indexes];
        [self.table deleteRowsAtIndexPaths:indexArr withRowAnimation:UITableViewRowAnimationTop];
        model.unfold = cell.unfold = NO;
        return;
    }

    [self loadNextDataWithUserId:model.userId Completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (!succ) {
            [SVProgressHUD showErrorWithStatus:message];
            return ;
        }
        NSArray<MyTeamListModel *> *modelArr = [MyTeamListModel arrayOfModelsFromDictionaries:result];

        [modelArr enumerateObjectsUsingBlock:^(MyTeamListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.level = model.level + 1;
            [indexes addIndex:++endIndex];
            [indexArr addObject:[NSIndexPath indexPathForRow:endIndex inSection:0]];
        }];

        [self.dataArr insertObjects:modelArr atIndexes:indexes];
        [self.table insertRowsAtIndexPaths:indexArr withRowAnimation:UITableViewRowAnimationTop];
        model.unfold = cell.unfold = YES;
    }];
}

#pragma mark - getter and setter
- (NSMutableArray<MyTeamListModel *> *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}


@end
